package com.example.alarm.mvvm.adapter

import android.widget.ImageView
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.alarm.R
import com.example.alarm.mvvm.activity.AlarmDetailActivity
import com.example.alarm.mvvm.bean.AlarmDetailBean
import com.example.login.mvvm.viewmodel.AlarmViewModel
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.util.FileUtils
import com.gsafety.libraryktx.util.GlideApp
import com.gsafety.libraryktx.util.GlideUtils
import java.io.File

class RvDownloadAdapter(data:List<AlarmDetailBean.DocsBean>): BaseQuickAdapter<AlarmDetailBean.DocsBean, BaseViewHolder>(
    R.layout.common_download_item_view,data) {
    private lateinit var mv: AlarmViewModel
    override fun convert(helper: BaseViewHolder?, item: AlarmDetailBean.DocsBean?) {
        var ivAttach = helper?.getView<ImageView>(R.id.item_attach_pic_iv)
        GlideUtils.getInstance(mContext).displayImage(item?.urlAddr.toString(),ivAttach!!)
        var filename = item?.fileName
        item?.urlAddr.toString().let{
            if(it.substring(it.lastIndexOf(".") + 1) == "mp4"){
                helper?.setVisible(R.id.iv_video,true)
                val attachDir = File(Constant.CACHE_DIR)
                var attachFile = File(attachDir.toString() + File.separator + "$filename")
                if(!attachFile.exists()){
                    mv.download(item?.urlAddr.toString())
                }
            }
        }
    }

    fun setViewModel(model: AlarmViewModel,activity: AlarmDetailActivity){
        mv = model
        mv.downloadValue.observe(activity, Observer {
            val attachDir = File(Constant.CACHE_DIR)
            // 下载后保存文件
            var filename = it.url?.substring(it.url?.lastIndexOf("/")!! + 1)
            var attachFile = File(attachDir.toString() + File.separator + "$filename")
            val file = FileUtils.streamToFile(it.body?.byteStream(), attachFile)
        })
    }
}